//
//  ZListForGoodsViewController.m
//  shopSN
//
//  Created by yisu on 16/9/3.
//  Copyright © 2016年 yisu. All rights reserved.
//

#import "ZListForGoodsViewController.h"
#import "ZGoodsSearchViewController.h"//商品搜索页面
#import "ZCommonGoodsInfoViewController.h"//商品信息页面

#import "ZListGoodsCell.h"

#import "ZYSLoginViewController.h"//亿速登录

@interface ZListForGoodsViewController ()<UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>
{
    UITableView *_tableView;
    UIView *footerView;
    UITextField *searchTF;
    
    
    
    NSString *_pointStr;//积分
    NSArray *_currentDataArray;//当前数据
    int _currentPage;//页数
}

/** 会员商品 数组 */
@property (nonatomic, strong) NSMutableArray *goodsArray;

@end

@implementation ZListForGoodsViewController



#pragma mark - ==== 页面设置 =====
- (void)viewWillAppear:(BOOL)animated {
    
    
    
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //初始 数据
    _currentPage = 1;
    _goodsArray = [NSMutableArray array];
    
    [self getData];
    
    
    [self initSubViews:self.mainMiddleView];
    
}


#pragma mark - 自定义导航栏中间内容
- (void)addNaviSubControllers:(UIView *)middleView {
    //middleView.backgroundColor = __TestGColor;
    
    //中间搜索框
    UIView *searchView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectW(middleView), CGRectH(middleView))];
    searchView.layer.borderWidth = 1;
    searchView.layer.borderColor = HEXCOLOR(0xdedede).CGColor;
    searchView.backgroundColor = HEXCOLOR(0xffffff);
    searchView.layer.cornerRadius = 5;
    [middleView addSubview:searchView];
    [self createSearchSubView:searchView];
    
}

//自定义 搜索视图 内部控件
- (void)createSearchSubView:(UIView *)btnView {
    
    
    //searchIV
    UIImageView *searchIV = [[UIImageView alloc] initWithFrame:CGRectMake(10, 7.5, 15, 15)];
    searchIV.image = MImage(@"sousuo");
    //searchIV.backgroundColor = __TestOColor;
    [btnView addSubview:searchIV];
    
//    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(CGRectXW(imageView)+5, 5, 70, CGRectH(btnView)-10)];
//    label.font = MFont(14);
//    label.textColor = HEXCOLOR(0x999999);
//    label.text = @"搜索商品";
//    [btnView addSubview:label];
    
    //searchTF
    searchTF = [[UITextField alloc] initWithFrame:CGRectMake(CGRectXW(searchIV)+5, 5, CGRectW(btnView)-CGRectW(searchIV)-25, CGRectH(btnView)-10)];
    [btnView addSubview:searchTF];
    //searchTF.backgroundColor = __TestGColor;
    searchTF.delegate = self;
    searchTF.font = MFont(14);
    searchTF.textColor = HEXCOLOR(0x333333);
    searchTF.clearButtonMode = UITextFieldViewModeWhileEditing;//小叉子
    searchTF.keyboardType = UIKeyboardTypeWebSearch;//web搜索模式
    searchTF.placeholder = _subCategoryName;
    
}

//中间主视图内子控件初始化
- (void)initSubViews:(UIView *)view {
    
    view.backgroundColor = HEXCOLOR(0xf0f0f0);
    
    //商品类表
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 5, CGRectW(view), CGRectH(view)-55)];
    [view addSubview:_tableView];
    _tableView.backgroundColor = __AccountBGColor;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.dataSource = self;
    _tableView.delegate   = self;
    
    footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 30, CGRectW(view), 30)];
    UILabel *endNoteLb = [[UILabel alloc] initWithFrame:CGRectMake(10, CGRectH(footerView)-20, CGRectW(footerView)-20, 20)];
    [footerView addSubview:endNoteLb];
    endNoteLb.font = MFont(14);
    endNoteLb.textAlignment = NSTextAlignmentCenter;
    endNoteLb.text = @"没有更多数据了 ...";
    footerView.hidden = YES;
    _tableView.tableFooterView = footerView;
    
    
    //刷新控件
    //[_tableView addHeaderWithTarget:self action:@selector(refreshGoodsData)];//下拉刷新
    [_tableView addFooterWithTarget:self action:@selector(loadMoreGoodsData)];//上拉加载更多
    
}


#pragma mark - ===== tableView DataSource and Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //return 1;
    return _goodsArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ZListGoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ListGoodsCell"];
    
    if (!cell) {
        cell = [[ZListGoodsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ListGoodsCell"];
        
    }
    //test data
    //cell.pointLb.text = [NSString stringWithFormat:@"返利：%@",_pointStr];
    
    //load data
    ZGoodsModel *goods = [[ZGoodsModel alloc] init];
    goods = _goodsArray[indexPath.row];
    
    [cell setGoodsInfo:_goodsArray[indexPath.row]];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 130;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //判断用户是否登录
//    if (IsNilString([UdStorage getObjectforKey:Userid])) {
//        [self loginAction];
//    }else {
        ZGoodsModel *goods = [[ZGoodsModel alloc] init];
        goods = _goodsArray[indexPath.row];
        
        
        ZCommonGoodsInfoViewController *vc = [[ZCommonGoodsInfoViewController alloc] init];
        vc.comGoodsID = goods.goodsID;
        NSLog(@"点击行数:%ld====>选择商品:%@===>进入普通商品信息页面",(long)indexPath.row, goods.goodsTitle);
        [self.navigationController pushViewController:vc animated:YES];

//    }
    
    
    
}





#pragma mark - 获取数据
- (void)getData {
    //test Data
    //_pointStr = @"100积分";
    
    if (IsNilString(_subCategoryID) && IsNilString(_mainCategoryID)) {
        [SXLoadingView showAlertHUD:@"数据信息不全，请重新加载" duration:SXLoadingTime];
        return;
        
    }else{
        if (_subCategoryID != nil) {//二级分类数据请求
            [self subCategoryDataRequestWithID:_subCategoryID andPageNum:_currentPage];
        }else{                      //一级分类全数据请求
            [self mainCategoryAllDataRequestWithID:_mainCategoryID andPageNum:_currentPage];
        }
    }
    
    
}

#pragma mark - 一级分类全数据请求
- (void)mainCategoryAllDataRequestWithID:(NSString *)cateID andPageNum:(int)pageNum {
    //115.159.146.202/api/goods.php?action=one_level_goods&id=19&page=1&pagesize=10&format=array
    NSString *page = [NSString stringWithFormat:@"%d",pageNum];
//    NSString *pageSize = @"10";
    NSDictionary *params = @{@"id":cateID,
                             @"page":page};
    [ZHttpRequestService POSTGoods:@"Goods/classGoods" withParameters:params success:^(id responseObject, BOOL succe, NSDictionary *jsonDic) {
        if (succe) {
            if (IsNull(jsonDic[@"data"])) {
                [SXLoadingView showAlertHUD:@"该类商品数据为空" duration:1.5];
                return ;
            }
            NSArray *array = [Parse parseGoodsList:jsonDic[@"data"]];
            _currentDataArray = array;
            [_goodsArray addObjectsFromArray:array];
            
            [_tableView reloadData];
            
        }else {
            
            NSString *message = jsonDic[@"message"];
            //[SXLoadingView showAlertHUD:message duration:SXLoadingTime];
            if ([message isEqualToString:@"查询失败"]) {
                footerView.hidden = NO;
                [_tableView reloadData];
            }
        }
    } failure:^(NSError *error) {
        [SXLoadingView showAlertHUD:@"请求失败" duration:SXLoadingTime];
        
    } animated:NO withView:nil];
    
    
    
    
}
#pragma mark - 二级分类数据请求
- (void)subCategoryDataRequestWithID:(NSString *)cateID andPageNum:(int)pageNum {
    //115.159.146.202/api/goods.php?action=goods_list&id=46
    NSString *page = [NSString stringWithFormat:@"%d",pageNum];
    
//    NSString *pageSize = @"10";
//    NSDictionary *params = @{@"id":cateID,
//                             @"page":page,
//                             @"pagesize":pageSize};
    NSDictionary *params = @{@"id":cateID};
    [ZHttpRequestService POSTGoods:@"Goods/goodsList" withParameters:params success:^(id responseObject, BOOL succe, NSDictionary *jsonDic) {
        if (succe) {
            if (IsNull(jsonDic[@"data"])) {
                [SXLoadingView showAlertHUD:@"该类商品数据为空" duration:1.5];
                return ;
            }
            NSArray *array = [Parse parseGoodsList:jsonDic[@"data"]];
            
            _currentDataArray = array;
            [_goodsArray addObjectsFromArray:array];
            
            //[self initSubViews:self.mainMiddleView];
            [_tableView reloadData];
            
        }else {
            
            NSString *message = jsonDic[@"message"];
            if ([message isEqualToString:@"查询失败"]) {
                footerView.hidden = NO;
                [_tableView reloadData];
            }else {
                [SXLoadingView showAlertHUD:message duration:SXLoadingTime];
                //[self backAciton];
            }
            
        }
    } failure:^(NSError *error) {
        [SXLoadingView showAlertHUD:@"请求失败" duration:SXLoadingTime];
        
    } animated:NO withView:nil];

}


#pragma mark - ===== 刷新控件设置内容 =====
#pragma mark - 上拉加载更多
- (void)collectionViewFootLoadAction {
    
    [self loadMoreGoodsData];
}


//加载更多商品
- (void)loadMoreGoodsData {
    NSLog(@"旅游商品 评价页面 加载更多");
    [_tableView footerEndRefreshing];
    if (_currentDataArray.count == 10) {
        _currentPage++;
        [self getData];
    }else{

        _tableView.footerHidden = YES;
        _tableView.tableFooterView.hidden = NO;
    }
    
    
    
}


#pragma mark - 下拉刷新数据
- (void)refreshGoodsData {
    NSLog(@"旅游商品 简介页面 下拉刷新");
    [_tableView headerEndRefreshing];
    _tableView.footerHidden = NO;
    _tableView.tableFooterView.hidden = YES;
    //初始化 数据
    _currentPage = 1;
    [_goodsArray removeAllObjects];

    [self getData];
    
}


#pragma mark - 进入登录页面
-(void)loginAction{
    
//    ZLoginViewController *vc = [[ZLoginViewController alloc] init];
    ZYSLoginViewController *vc = [[ZYSLoginViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - ===== TextFiled Delegate =====
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (IsNilString(textField.text)) {
        [SXLoadingView showAlertHUD:@"请输入搜索内容" duration:SXLoadingTime];
    }else {
        ZGoodsSearchViewController *vc = [[ZGoodsSearchViewController alloc] init];
        vc.searchStr = textField.text;
        [self.navigationController pushViewController:vc animated:YES];
        
    }
    
    [textField resignFirstResponder];
    return YES;
}



- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (searchTF) {
        [self.view endEditing:YES];
    }
}


#pragma mark - ==== others =====
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
